package com.example.springboottest.student.service.impl;

import com.example.springboottest.base.AbstractService;
import com.example.springboottest.student.service.LockService;
import com.example.springboottest.util.IdUtil;
import com.example.springboottest.util.RedisTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisLockServiceImpl extends AbstractService implements LockService {
    private static final int expireTime = 10 * 1000;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean getDistributeLock(String lockKey) {
        Jedis jedis = jedisPool.getResource();
        String value = jedis.get(lockKey);
        logger.info("lockKey's value={}\t", value);
        boolean isSuccess = false;
        try {
            isSuccess = RedisTool.tryGetDistributedLock(jedis, lockKey, IdUtil.getUUID(), expireTime);
        } catch (Exception e) {
            logger.info("获取分布式锁错误！");
        } finally {
            jedisPool.returnResource(jedis);
        }
        return isSuccess;
    }

    @Override
    public boolean releaseDistributedLock(String lockKey, String requestId) {
        Jedis jedis = jedisPool.getResource();
        String value = jedis.get(lockKey);
        logger.info("lockKey's value={}\t", value);
        boolean isSuccess = false;
        try {
            isSuccess = RedisTool.releaseDistributedLock(jedis, lockKey, requestId);
        } catch (Exception e) {
            logger.info("释放分布式锁错误！");
        } finally {
            jedisPool.returnResource(jedis);
        }
        return false;
    }
}
